class Api::StoreOrdersController < Api::BaseController
  before_action :set_store_customer, :set_normal_store_id, :set_cart, only: [:create]
  before_action :set_store_order, only: [:confirm, :to_process, :to_mail, :cancel, :show]
  def create
    @status = BuildOrderService.call(@cart, @customer, store_order_params)
    if @status.success?
      @status.obj.order_push
      redirect_to sales_store_orders_path(store_id: @normal_store_id), notice: @status.message
    else
      redirect_to new_sales_store_order_path(store_id: @normal_store_id), notice: @status.message
    end
  end

  def confirm
    @store_order.confirming!
    render json: {status: true}
  end

  def to_process
    @store_order.to_process!
    render json: {status: true}
  end

  def to_mail
    @store_order.to_mail!
    render json: {status: true}
  end

  def cancel
    @store_order.cancel!
    render json: {status: true}
  end

  def show
    respond_with @store_order, location: nil
  end

  def data
    @store_orders = current_store.orders.by_month_days.available.order("created_at desc")
    # cache_key = "api:orders:#{current_store.id}:#{@store_orders.maximum(:updated_at)}"
    # Rails.logger.info "有效的订单数量是#{@store_orders.count(:id)},缓存key是#{@store_orders.maximum(:updated_at)}"
    # result = Rails.cache.read(cache_key)
    # if !result.present?
    #   Rails.logger.info "这里是重新载入缓存"
    #   result = Rails.cache.write(cache_key, @store_orders.pluck(:created_at))
    # end
    render json: {store_orders: @store_orders.pluck(:created_at)}
  end

  private
  def store_order_params
    params[:store_order][:store_id] = @normal_store_id
    params.require(:store_order).permit(:store_id,
                                        :store_customer_id,
                                        :phone_number,
                                        :company_name,
                                        :user_name,
                                        :remark,
                                        :address
                                        )
  end

  def set_store_customer
    @customer ||= current_customer
  end

  def set_normal_store_id
    @normal_store_id = decode(params[:store_order][:store_id])
  end

  def set_cart
    @cart ||= current_cart
  end

  def set_store_order
    @store_order = StoreOrder.find(params[:id])
  end
end
